package net.jacqeush.mini.rpc.codec;



import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import net.jacqeush.mini.rpc.tools.SerializationUtils;


/**
 * @author Jacquesh
 * @version 1.0
 * @date 2020/10/16 3:15
 */
public class Encoder  extends MessageToByteEncoder{
    private Class<?> genericsClass;
    public  Encoder(Class<?> genericsClass ){
        this.genericsClass=genericsClass;
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
     if (genericsClass.isInstance(msg)){
         byte[] data = SerializationUtils.serialize(msg);
         // 消息分为：1.包头 (数据包长度)  2.包体(数据包内容)
         byteBuf.writeInt(data.length);
         byteBuf.writeBytes(data);
     }
    }
}
